package persistence.dataAccessObjects;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.sql.DataSource;

import persistence.dataAccessObjects.interfaces.IGenericDAO;

public abstract class GenericDAO implements IGenericDAO {
	protected DataSource datasource;
	protected Connection connection;
	protected static int pooledCount, nonPooledCount;
	
	public GenericDAO()
	{
		connection = null;
		datasource = null;
		
		try {
			init();
		}
		
		catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	protected final void init() throws ServletException 
	{
		try
		{
			InitialContext initialContext = new InitialContext();
//			if ( initialContext == null )
//			{
//				final String message = "There was no InitialContext in DBBroker. We're about to have some problems.";
//				System.err.println("*** " + message);
//				throw new Exception(message);
//			}
			
			// DB-Ressource nachschlagen
			datasource = (DataSource) initialContext.lookup( "java:/comp/env/jdbc/mysql" );

			if (datasource == null)
			{
				String message = "Could not find our DataSource in DBBroker. We're about to have problems.";
				System.err.println("*** " + message);
				throw new Exception(message);
			}
		}
		catch (Exception e)
		{
			throw new ServletException(e.getMessage());
		}	
	}
	
	protected final synchronized Connection getConnection(boolean pooledConnection) throws SQLException 
	{
		return datasource.getConnection();
	}

	/**
	 * Must close the database connection to return it to the pool.
	 */
	protected static synchronized void freeConnection(Connection connection)
	{
		try {
			connection.close();
		}
		
		catch (Exception e)
		{
			System.err.println("DBBroker: Threw an exception closing a database connection");
			e.printStackTrace();
		}
	}

	protected void finalize() throws Throwable
	{
	  //do finalization here
	  super.finalize(); //not necessary if extending Object.
	  GenericDAO.freeConnection(connection);
	} 
}
